package com.webkaifa.utility;

import java.util.LinkedList;
import java.util.ListIterator;

public class EventQueue {
    private int maxQueueSize;
    private LinkedList queueData;
    private Object mutex;

    public EventQueue()
    {
        maxQueueSize = 0;
        queueData = new LinkedList();
        mutex = this;
    }

    public EventQueue(int maxSize)
    {
        maxQueueSize = 0;
        queueData = new LinkedList();
        maxQueueSize = maxSize;
        mutex = this;
    }

    public int size()
    {
        int i;
        synchronized(mutex)
        {
           i = queueData.size();
        }
        
        return i;
    }

    public boolean isEmpty()
    {
        boolean flag;
        synchronized(mutex)
        {
           flag = queueData.isEmpty();
        }
        return flag;
    }

    public Object dequeue()
    {
        Object obj1;
        synchronized(mutex)
        {
            Object first = null;
            if(size() > 0)
                first = queueData.removeFirst();
            obj1 = first;
        }
        
        return obj1;
    }

    public Object dequeue(Object obj)
    {
        Object found = null;
        synchronized(mutex)
        {
            found = find(obj);
            if(found != null)
                queueData.remove(found);
        }
        return found;
    }

    public void enqueue(Object obj)
       throws IndexOutOfBoundsException    
    {
        synchronized(mutex)
        {
            if(maxQueueSize > 0 && size() >= maxQueueSize)
                throw new IndexOutOfBoundsException("Queue is full. Element not added.");
            queueData.add(obj);
        }
    }

    public Object find(Object obj)
    {
        synchronized(mutex)
        {
            for(ListIterator iter = queueData.listIterator(0); iter.hasNext();)
            {
                Object current = iter.next();
                if(current.equals(obj))
                {
                    Object obj2 = current;
                    return obj2;
                }
            }
        }
        return null;
    }
}


